﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Kaskelot.SP.Core
{
	public static class SPExtensions
	{
		public static bool IsFeatureActivated(this SPWeb web, Guid featureId)
		{
			return web.Features[featureId] != null;
		}

		public static bool IsFeatureActivated(this SPSite site, Guid featureId)
		{
			return site.Features[featureId] != null;
		}

        public static void Reactivate(this SPFeatureCollection col, Guid featureId)
        {
            if (col.Any(f => f.DefinitionId == featureId) == true)
                col.Remove(featureId);
            col.Add(featureId);
        }

		public static bool ContainsSiteGroup(this SPWeb web, string groupName)
		{
			return (from SPGroup g in web.SiteGroups
					where g.Name.ToLower() == groupName.ToLower()
					select g).Any();
		}

		public static bool IsPrincipalInRole(this SPWeb web, SPPrincipal principal, SPRoleDefinition roleDef)
		{
			return web.RoleAssignments.Cast<SPRoleAssignment>().Any(ra =>
				ra.Member.LoginName.ToLower() == principal.LoginName.ToLower()
				&& ra.RoleDefinitionBindings.Cast<SPRoleDefinition>().Any(rd => rd.Name.ToLower() == roleDef.Name.ToLower()));
		}

		public static bool ContainsRoleDefinition(this SPWeb web, string nameOfDefinition)
		{
			return web.RoleDefinitions.Cast<SPRoleDefinition>().Any(rd => rd.Name.ToLower() == nameOfDefinition.ToLower());
		}
	}
}
